import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    nav: [],
    goods: [],
    details: {},
    money: 0,
    cart: JSON.parse(localStorage.getItem('carts')) || [],
  },
  mutations: {
    getNav(state, item) {
      state.nav = [...item];
    },
    getData(state, item) {
      state.goods = [...item];
    },
    getDetails(state, obj) {
      obj.res.map(ele => {
        if (ele.data.mtWmPoiId == obj.id) {
          state.details = ele;
        }
      });
    },
    addCart(state, item) {
      var flag = false;
      state.cart.map(ele => {
        console.log(ele);
        if (ele.carts.spuId == item.spuId) {
          flag = true;
          ele.num++;
        }
      })

      if (!flag) {
        state.cart.push({
          num: 1,
          carts: item
        })
      }

      localStorage.setItem('carts', JSON.stringify(state.cart))
    },

    //步进器发生改变执行的操作
    onChange(state) {
      localStorage.setItem('carts', JSON.stringify(state.cart));
      // state.money = 0;


    },

    //点击弹出购物车
    showCart(state) {

    }
  },
  actions: {
    getNav(context) {
      axios.get("http://localhost:8080/category.json")
        .then(res => {
          context.commit('getNav', res.data.data.kingkongList)
        })
    },
    getData(context) {
      axios.get("http://localhost:8080/listData.json")
        .then(res => {
          context.commit('getData', res.data.data.shopList);
        })
    },
    getDetails(context, id) {
      axios.get("http://localhost:8080/shopdetails.json", {
        id: id,
      }).then(res => {
        context.commit('getDetails', { id: id, res: res.data });
      })
    },
    addCart(context, item) {
      context.commit('addCart', item);
    },
    onChange(context) {
      context.commit('onChange');
    },
    showCart(context) {
      context.commit('showCart');
    }
  },
  modules: {
  }
})
